package com.example.musicplayer;

import android.app.Activity;
import android.os.Handler;

import java.util.Stack;

//管理activity页面栈
public class ActivityStackManager {
    private static ActivityStackManager sInstance;
    //存放activity的栈
    private Stack<Activity> mActivities;
    private Handler mHandler = new Handler();

    private ActivityStackManager() {
    }

    public static ActivityStackManager getInstance() {
        if (sInstance == null)
            sInstance = new ActivityStackManager();
        return sInstance;
    }

    public int getStackSize() {
        if (mActivities == null)
            return 0;
        return mActivities.size();
    }

    //得到主activity的引用
    public Activity getMainActivity() {
        if (mActivities != null && !mActivities.isEmpty()) {
            return mActivities.firstElement();
        }
        return null;
    }

    public void addActivity(Activity activity) {
        if (mActivities == null)
            mActivities = new Stack<Activity>();
        if (activity != null)
            mActivities.push(activity);
    }

    public void removeActivity(Activity activity) {
        if (mActivities != null && mActivities.size() > 0)
            mActivities.remove(activity);
    }

    //获取栈顶的activity
    public Activity getTopActivity() {
        if (mActivities != null && mActivities.size() > 0)
            return mActivities.peek();
        return null;
    }

    //退出当前应用
    public void exit() {
        if (mActivities != null) {
            Activity activity;
            while (mActivities.size() > 0) {
                activity = mActivities.pop();
                if (activity != null && !activity.isFinishing())
                    activity.finish();
            }
        }
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                android.os.Process.killProcess(android.os.Process.myPid());
                System.exit(0);
            }
        }, 1000);
    }
}